<template>
  <div class="order-management">
    <!-- 查询栏（复用QueryBar组件） -->
    <QueryBar @query="handleQuery" />
    <GenericManagement
      :dataList="orderList"
      :columns="columns"
      :formFields="formFields"
      :canAdd="true"
      :canEdit="true"
      :canDelete="true"
      @add="handleAddOrder"
      @edit="handleEditOrder"
      @delete="handleDeleteOrder"
      primaryKey="order_id"
      entityName="订餐"
    />
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import GenericManagement from '../components/GenericManagement.vue';
import QueryBar from '../components/QueryBar.vue';
import axios from 'axios';

const orderList = ref([]);
const currentQueryId = ref(null); // 新增：当前查询的订单ID

// 表格列配置（与实验指导书组件规范一致）
const columns = [
  { prop: 'order_id', label: '订单号', width: '100' },
  { prop: 'user_id', label: '用户ID', width: '120' },
  { prop: 'order_date', label: '下单日期', width: '120' },
  { prop: 'delivery_date', label: '配送日期', width: '120' },
  { prop: 'order_status', label: '状态', width: '120' },
  { prop: 'total_price', label: '总价', width: '120' },
  { prop: 'ordered_foods', label: '订餐内容', width: '200' }
];

// 表单字段配置（新增订单ID字段）
const formFields = [
  { prop: 'order_id', label: '订单号', type: 'input' }, // 新增ID字段
  { prop: 'user_id', label: '用户ID', type: 'input' },
  { prop: 'order_date', label: '下单日期', type: 'input' }, // 建议改为日期选择组件
  { prop: 'delivery_date', label: '配送日期', type: 'input' }, // 建议改为日期选择组件
  {
    prop: 'order_status',
    label: '状态',
    type: 'select', // 改为下拉选择框
    options: [{ label: '待处理', value: 'pending' }, { label: '已完成', value: 'completed' }]
  },
  { prop: 'total_price', label: '总价', type: 'input' },
  { prop: 'ordered_foods', label: '订餐内容', type: 'input' }
];

// 获取订单列表（含查询逻辑）
const fetchOrderList = async (id = null) => {
  try {
    let url = 'http://localhost:8080/DietManagementSystem_war/admin/order/list';
    if (id) {
      url = `http://localhost:8080/DietManagementSystem_war/admin/order/${id}`; // 按ID查询接口
    }
    const response = await axios.get(url);
    orderList.value = id ? [response.data] : response.data;
  } catch (error) {
    console.error('获取订单数据失败:', error);
  }
};

// 处理查询事件
const handleQuery = (id) => {
  currentQueryId.value = id;
  fetchOrderList(id); // 触发查询
};

// 初始化加载
onMounted(() => {
  fetchOrderList();
});

// 添加订单（修正表单字段，包含ID）
const handleAddOrder = async (newOrder) => {
  try {
    if (!newOrder.order_id) {
      newOrder.order_id = Date.now(); // 临时ID生成
    }
    await axios.post('http://localhost:8080/DietManagementSystem_war/admin/order/add', newOrder);
    fetchOrderList();
  } catch (error) {
    console.error('添加订单失败:', error);
  }
};

// 编辑订单（修正接口路径为PUT）
const handleEditOrder = async (updatedOrder) => {
  try {
    await axios.put(`http://localhost:8080/DietManagementSystem_war/admin/order/update/${updatedOrder.order_id}`, updatedOrder);
    fetchOrderList();
  } catch (error) {
    console.error('编辑订单失败:', error);
  }
};

// 删除订单（保持原有逻辑）
const handleDeleteOrder = async (orderId) => {
  try {
    await axios.delete(`http://localhost:8080/DietManagementSystem_war/admin/order/delete/${orderId}`);
    fetchOrderList();
  } catch (error) {
    console.error('删除订单失败:', error);
  }
};
</script>

<style scoped>
.order-management { padding: 20px; }
</style>